<template>
    
    <!-- :height="height" -->
	<u-popup v-model="value" mode="bottom" :popup="false" :mask="mask" :closeable="false" :safe-area-inset-bottom="true"
	 close-icon-color="#ffffff" :z-index="uZIndex" :maskCloseAble="maskCloseAble" @close="close">
        <view class="pop-title">
            <text></text>
            <view class="title">选择地区</view>
            <u-icon name="close" @click="close"></u-icon>
        </view>
        
        
		<u-tabs v-if="value" barColor="#2d8cff" inactiveColor="rgba(47,53,65,.5)" bar-height="10" height="70"   barBottom="6" :list="genTabsList" :is-scroll="true" :current="tabsIndex" @change="tabsChange" ref="tabs"></u-tabs>
		<view class="area-box">
        
			<view class="u-flex" :class="{ 
                'change1':isChange,
                'change2':isChange2
             }">
				<view class="area-item" v-if="level>=1">
					<view class="u-padding-10 u-bg-gray" style="height: 100%;">
						<scroll-view :scroll-y="true" style="height: 100%">
							<u-cell-group>
								<u-cell-item v-for="(item,index) in provinces" :title="item.label" padding="10rpx 20rpx" :arrow="false" :index="index" :key="index"
								 @click="provinceChange">
									<u-icon v-if="isChooseP&&province===index" slot="right-icon" size="34" name="checkbox-mark"></u-icon>
								</u-cell-item>
							</u-cell-group>
						</scroll-view>
					</view>
				</view>
				<view class="area-item" v-if="level>=2">
					<view class="u-padding-10 u-bg-gray" style="height: 100%;">
						<scroll-view :scroll-y="true" style="height: 100%">
							<u-cell-group v-if="isChooseP">
								<u-cell-item v-for="(item,index) in citys" :title="item.label" padding="10rpx 20rpx" :arrow="false" :index="index" :key="index"
								 @click="cityChange">
									<u-icon v-if="isChooseC&&city===index" slot="right-icon" size="34" name="checkbox-mark"></u-icon>
								</u-cell-item>
							</u-cell-group>
						</scroll-view>
					</view>
				</view>

				<view class="area-item" v-if="level>=3 && areas.length">
					<view class="u-padding-10 u-bg-gray" style="height: 100%;">
						<scroll-view :scroll-y="true" style="height: 100%">
							<u-cell-group v-if="isChooseC">
								<u-cell-item v-for="(item,index) in areas" :title="item.label" padding="10rpx 20rpx" :arrow="false" :index="index" :key="index"
								 @click="areaChange">
									<u-icon v-if="isChooseA&&area===index" slot="right-icon" size="34" name="checkbox-mark"></u-icon>
								</u-cell-item>
							</u-cell-group>
						</scroll-view>
					</view>
				</view>
                
                <view class="area-item" v-if="level>=4 && streets.length">
                	<view class="u-padding-10 u-bg-gray" style="height: 100%;">
                		<scroll-view :scroll-y="true" style="height: 100%">
                			<u-cell-group v-if="isChooseA">
                				<u-cell-item v-for="(item,index) in streets" :title="item.label" padding="10rpx 20rpx" :arrow="false" :index="index" :key="index"
                				 @click="streetsChange">
                					<u-icon v-if="isChooseS&&street===index" slot="right-icon" size="34" name="checkbox-mark"></u-icon>
                				</u-cell-item>
                			</u-cell-group>
                		</scroll-view>
                	</view>
                </view>
			</view>
		</view>
	</u-popup>
</template>

<script>
	// import provinces from "uview-ui/libs/util/province.js";
	// import citys from "uview-ui/libs/util/city.js";
	// import areas from "uview-ui/libs/util/area.js";
	/**
	 * city-select 省市区级联选择器
	 * @property {String Number} z-index 弹出时的z-index值（默认1075）
	 * @property {Boolean} mask-close-able 是否允许通过点击遮罩关闭Picker（默认true）
	 * @property {String} default-region 默认选中的地区，中文形式
	 * @property {String} default-code 默认选中的地区，编号形式
	 */
	export default {
		name: 'u-city-select',
		props: {
			// 通过双向绑定控制组件的弹出与收起
			value: {
				type: Boolean,
				default: false
			},
			// 默认显示的地区，可传类似["河北省", "秦皇岛市", "北戴河区"]
			defaultRegion: {
				type: Array,
				default () {
					return [];
				}
			},
			// 默认显示地区的编码，defaultRegion和areaCode同时存在，areaCode优先，可传类似["13", "1303", "130304"]
			areaCode: {
				type: Array,
				default () {
					return [];
				}
			},
			// 是否允许通过点击遮罩关闭Picker
			maskCloseAble: {
				type: Boolean,
				default: true
			},
            
            mask: {
            	type: Boolean,
            	default: true,
            },
			// 弹出的z-index值
			zIndex: {
				type: [String, Number],
				default: 0
			},
            height: {
            	type: [String, Number],
            	default: 500
            },
            //默认三级
            level: {
            	type: [String, Number],
            	default: 3
            },
		},
		data() {
			return {
				cityValue: "",
				isChooseP: false, //是否已经选择了省
				province: 0, //省级下标
				provinces: [],
				isChooseC: false, //是否已经选择了市
				city: 0, //市级下标
				citys: [],
				isChooseA: false, //是否已经选择了区
				area: 0, //区级下标
				areas: [],
				tabsIndex: 0,
                streets:[],
                isChooseS:false,//是否选择街道
                street:0,
			}
		},
	  async	mounted() {
			this.init();
            let list = await this.getInit();
            this.provinces = list;
            this.province = 0;
            this.isChooseP = true;
            let city = await this.getInit(list[0].value);
            this.citys = city;
            // this.tabsIndex = 1;
		},
		computed: {
            boxheight(){
                return this.height - 120
            },
			isChange() {
				return this.tabsIndex > 1;
			},
            isChange2() {
            	return this.tabsIndex > 2;
            },
			genTabsList() {
				let tabsList = [{
					name: "请选择"
				}];
				if (this.isChooseP) {
					tabsList[0]['name'] = this.provinces[this.province]['label'];
					tabsList[1] = {
						name: "请选择"
					};
				}
				if (this.isChooseC &&  this.citys.length) {
					tabsList[1]['name'] = this.citys[this.city]['label'];
                    if(this.level >= 3 && this.areas.length){
                        tabsList[2] = {
                        	name: "请选择"
                        };
                    }
				}
				if (this.isChooseA && this.level >= 3  && this.areas.length) {
					tabsList[2]['name'] = this.areas[this.area]['label'];
                    if(this.level >= 4 && this.streets.length){
                        tabsList[3] = {
                        	name: "请选择"
                        };
                    }
				}
                
                if (this.isChooseS && this.level >= 4) {
                	tabsList[3]['name'] = this.streets[this.street]['label'];
                }
				return tabsList;
			},
			uZIndex() {
				// 如果用户有传递z-index值，优先使用
				return this.zIndex ? this.zIndex : this.$u.zIndex.popup;
			}
		},
		methods: {
            //回显
            async showInit(ids=[]){
               let index=0;
               const obj = {
                   0:{
                       list:'provinces',
                       idx:'province',
                       choose:'isChooseP',
                   },
                   1:{
                       list:'citys',
                       idx:'city',
                       choose:'isChooseC',
                   },
                   2:{
                       list:'areas',
                       idx:'area',
                       choose:'isChooseA',
                   },
                   3:{
                       list:'streets',
                       idx:'street',
                       choose:'isChooseS',
                   }
               }
               
               if(!this.provinces.length){
                   this.provinces = await this.getInit();
               }
               
               while(ids.length){
                   const head = ids.shift();
                   let data = obj[index]
                   let listName = data['list'];
                   let parent =  obj[index-1] ?  obj[index-1] : null
                   let pid = parent ? this[parent['list']][this[parent['idx']]].value : null;
                   let list = this[listName].length ? this[listName] : await this.getInit(pid);
                   let cur = list.findIndex(item=>head == item.value);
                   this[listName] = list;
                   this[data['idx']] = cur;
                    this[data['choose']] = true;
                   index++
               }
               console.log('index', index);
                this.tabsIndex = index-1;
            },
            async getInit(id=0){
                let params  = {};
                let list = [];
                const res = await this.$api.clist({
                    id
                });
				list = res.data.data.map(item=>{
					return {
						label:item.name,
						value:item.id,
						pid:item.pid,
					}
				})
                return new Promise((qres, jres)=>{
                    qres(list)
                })
            },
			async init() {
				if (this.areaCode.length == 3) {
					this.setProvince("", this.areaCode[0]);
					this.setCity("", this.areaCode[1]);
					this.setArea("", this.areaCode[2]);
				} else if (this.defaultRegion.length == 3) {
					this.setProvince(this.defaultRegion[0], "");
					this.setCity(this.defaultRegion[1], "");
					this.setArea(this.defaultRegion[2], "");
				};
			},
			setProvince(label = "", value = "") {
				this.provinces.map((v, k) => {
					if (value ? v.value == value : v.label == label) {
						this.provinceChange(k);
					}
				})
			},
			setCity(label = "", value = "") {
				this.citys.map((v, k) => {
					if (value ? v.value == value : v.label == label) {
						this.cityChange(k);
					}
				})
			},
			setArea(label = "", value = "") {
				this.areas.map((v, k) => {
					if (value ? v.value == value : v.label == label) {
						this.isChooseA = true;
						this.area = k;
					}
				})
			},
			close() {
				this.$emit('input', false);
                this.$emit('close', false);
			},
			tabsChange(index) {
				this.tabsIndex = index;
			},
		 async	provinceChange(index) {
                let city = await this.getInit(this.provinces[index].value);
				this.isChooseP = true;
				this.isChooseC = false;
				this.isChooseA = false;
                this.isChooseS = false;
				this.province = index;
                this.citys = city;
                this.areas = [];
                this.street = [];
				this.tabsIndex = 1;
			},
			async cityChange(index) {
                this.street = [];
                 this.areas = [];
                 this.isChooseA = false;
                  this.isChooseS = false;
                 let areas = await this.getInit(this.citys[index].value);
				this.isChooseC = true;
				this.city = index;
                if(this.level < 3 || !areas.length){
                    let result = {};
                    result.province = this.provinces[this.province];
                    result.city = this.citys[this.city];
                   
                    this.tabsIndex = 1;
                    this.$emit('city-change', result);
                    this.close();
                    return
                }
                console.log('areas',areas)
                this.areas = areas;
                 this.tabsIndex = 2;
			},
			async areaChange(index) {
                this.isChooseS = false;
                  this.street = [];
                 let streets = await this.getInit(this.areas[index].value);
				this.isChooseA = true;
				this.area = index;
				let result = {};
				result.province = this.provinces[this.province];
				result.city = this.citys[this.city];
				result.area = this.areas[this.area];
                if(this.level < 4){
                  this.$emit('city-change', result);
                  this.close();
                    return
                }
                 this.isChooseS = false;
                this.streets = streets;
                this.tabsIndex = 3
			},
           async  streetsChange(index){
                this.isChooseS = true;
                this.street = index;
                let result = {};
                result.province = this.provinces[this.province];
                result.city = this.citys[this.city];
                result.area = this.areas[this.area];
                result.street = this.streets[this.street];
                  this.$emit('city-change', result);
                  this.close();
            },
		}

	}
</script>
<style lang="scss">
    .pop-title{
        display: flex;
        justify-content: space-between;
        padding: 10rpx 20rpx 0;
        height: 60rpx;
        align-items: center;
        .title{
            font-size: 16px;
            font-weight: bold;
        }
    }
	.area-box {
		width: 100%;
		overflow: hidden;
		height: 400rpx;
        
		>view {
			width: 200%;
			transition: transform 0.3s ease-in-out 0s;
			transform: translateX(0);
			&.change1 {
				transform: translateX(-25%);
			}
            &.change2 {
                transform: translateX(-50%);
            }
		}

		.area-item {
			width: 25%;
			height: 400rpx;
		}
	}
</style>
